<!--
 * @Author: lsjweiyi 759209794@qq.com
 * @Date: 2024-04-05 20:37:47
 * @LastEditors: lsjweiyi 759209794@qq.com
 * @LastEditTime: 2024-04-06 18:52:35
 * @FilePath: \web-ssg\components\fileUpload.vue
 * @Description: 单文件上传组件
-->

<template>
    <div style="display: inline-flex; flex-direction: column">
        <input id="file" ref="inputRef" type="file" @change="FileChange" style="display: none" accept="image/*" />
        <button @click="inputRef.click()" class="button" :disabled="props.selectDisabled">选择文件</button>
        <button @click="uploadFile" :disabled="!file || (!isFileChange && props.disabled)" :loading="props.loading"
            class="button green">
            <div class="blocks" v-show="props.loading">
                <div class="block orange"></div>
                <div class="block blue"></div>
            </div>
            <span v-show="!props.loading">
                上传处理
            </span>
        </button>
    </div>
</template>
<script lang="ts" setup>
import "@/assets/button.scss";
import "@/assets/loading.css";
const file = ref<File | undefined>();
const inputRef = ref();
const isFileChange = ref(false);
const props = defineProps({
    loading: {
        type: Boolean,
        default: false,
    },
    disabled: { // 由父组件决定是否禁用上传按钮，默认禁用，他和isFileChange共同决定
        type: Boolean,
        default: true,
    },
    selectDisabled: {
        type: Boolean,
        default: false,
    }
});
function FileChange(e: any) {
    if (e.target.files[0]) {
        if (e.target.files[0].name == file.value?.name) {
            return;
        }
        emit("selectFile", e.target.files[0], (result = false) => {
            if (result) {
                file.value = e.target.files[0] as File;
                isFileChange.value = true;
            }
            // 清除input记录的文件，否则选择同一个文件无法再次出发该方法
            let obj = document.getElementById("file")
            if (obj) {
                (obj as HTMLInputElement).value = ""
            }
        });
    }
}
function uploadFile() {
    emit("uploadFile", file.value as File);
    isFileChange.value = false;
}
function clearFile() {
    file.value = undefined;
}
defineExpose({ clearFile });
const emit = defineEmits<{
    (e: "selectFile", file: File, fn: (result: boolean) => void): void;
    (e: "uploadFile", file: File): void;
}>();
</script>
<style>
.uploadButton {
    font-size: 40px;
    height: 60px;
    width: 320px;
    border-radius: 30px;
    margin-bottom: 20px;
}

.green {
    filter: hue-rotate(255deg) saturate(0.8);
}

.green:hover {
    filter: hue-rotate(255deg) saturate(1);
}

.green:active {
    filter: hue-rotate(255deg) saturate(1.2);
}
</style>
